package mailserver.sql;

import java.sql.*;
import java.util.ArrayList;
import mailcommon.entities.*;
import mailserver.server.exceptions.MailAddressExistsException;

public class AddressService {

    private static AddressService instance = null;

    private AddressService() {
    }

    public static AddressService getInstance() {
        if (instance == null) {
            instance = new AddressService();
        }
        return instance;
    }

    public ArrayList<MailAddress> select(String whereParams)
            throws SQLException {
        ArrayList<MailAddress> addresses = new ArrayList<MailAddress>();

        String query = "SELECT * "
                + " FROM address "
                + (!whereParams.isEmpty() ? " WHERE " + whereParams : "")
                + ";";
        Connection con = DBController.getInstance().createConnection();
        try {
            PreparedStatement stmt = con.prepareStatement(query);
            ResultSet rs = stmt.executeQuery();

            MailAddress curAddress;
            while (rs.next()) {
                int userId = Integer.parseInt(rs.getString("user_id"));
                curAddress = new MailAddress(
                        rs.getString("address"),
                        rs.getDate("creationDate").toString(),
                        userId);
                addresses.add(curAddress);
            }
            stmt.close();
        } finally {
            con.close();
        }

        return addresses;
    }

    public boolean exists(String address)
            throws SQLException {
        ArrayList<MailAddress> check = select(
                "address=\"" + address + "\"");
        return !check.isEmpty();
    }

    public void add(MailAddress address)
            throws SQLException, MailAddressExistsException {

        if (exists(address.getUniqueAddres())) {
            throw new MailAddressExistsException();
        }

        Connection con = DBController.getInstance().createConnection();
        try {
            String query = "insert into "
                    + "address(address,creationDate,user_id) "
                    + "values ("
                    + "\"" + address.getUniqueAddres() + "\", "
                    + "\"" + address.getCreationDateString() + "\", "
                    + address.getOwnerId()
                    + ")";

            PreparedStatement stmt = con.prepareStatement(query);
            stmt.execute();
            stmt.close();
        } finally {
            con.close();
        }
    }
}